$(function() {

})
var isInsert = $('.isInsert').val(),isDelete = $('.isDelete').val(),isUpdate = $('.isUpdate').val();
if (isInsert == null)
	isInsert = 0;
if (isUpdate == null)
	isUpdate = 0;
if (isDelete == null)
	isDelete = 0;
//获取当天的时间
function getNowTime() {
	var nowDate = new Date();
	var year = nowDate.getFullYear();
	var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
	var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
	return year + "-" + month + "-" + date + " 08:30:00";
}
//获取下一天的时间
function getNextTime() {
	var nowDate = new Date();
	var year = nowDate.getFullYear();
	var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
	var date = nowDate.getDate() + 1;
	date = date < 10 ? "0" + date : date;
	return year + "-" + month + "-" + date + " 08:30:00";
}

function ckBoxColor() {
	//复选框样式
	$("body").on("mouseenter", ".ckBox", function() {
		if($(this).hasClass("on")) {
			return;
		} else {
			$(this).addClass("hover");
		}
	})
	$("body").on("mouseout", ".ckBox", function() {
		$(this).removeClass("hover");
	})
	$("body").on("click", ".ckBox", function() {
		//如果是全选 
		if($(this).hasClass("allCKBox")) {
			$(this).toggleClass("on").removeClass("hover");
			if($(this).hasClass("on")) { //全选
				$(".tableList .ckBox").removeClass("hover").addClass("on");
			} else {
				$(".tableList .ckBox").removeClass("on");
			}
		} else {
			$(this).toggleClass("on").removeClass("hover");
		}
	})
}

function isNumber(value) { //验证是否为数字
	var patrn = /^\d+(\.\d+)?$/;
	return patrn.test(value);
}

//使用空字符串替换所有值为undefined的td
//ele 为表格的类名或id 或者父级对象
function replaceNull(ele) {
	var arrVal = $(ele).find("td");
	for(var i = 0; i < arrVal.length; i++) {
		if(arrVal[i].innerHTML == 'undefined') {
			arrVal[i].innerHTML = '';
		}
	}
}
//转换公司信息
function convertOrgToObj(objList) {
	var resultObj = new Object();
	$.each(objList, function (index, val) {
		resultObj[val.id] = val.originName;
	});
	return resultObj;
}
//转换枚举信息
function convertEnumToObj(objList) {
	var resultObj = new Object();
	$.each(objList, function (index, val) {
		resultObj[val.id] = val.name;
	});
	return resultObj;
}
/**显示值转换**/
function convertVal(val) {
	if (isNull(val))
		return '';
	else
		return val;
}

/**显示值转换**/
function convertNumber(val) {
	if (isNull(val))
		return 0;
	else
		return val;
}
function isNull(val) {
	if (val == null || val == undefined || val =='' || val == 'undefined' || val == 'null')
		return true;
	else
		return false;
}

function ckIsNull(ele) {
	var inputs = $(ele).find("input[lay-verify='required']");
	for(var i = 0; i < inputs.length; i++) {
		var str = $.trim(inputs[i].val());
		if(str == '' || str == null) {
			return 0;
		}
	}

}

function convertCurrency(money) {
	//汉字的数字
	var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
	//基本单位
	var cnIntRadice = new Array('', '拾', '佰', '仟');
	//对应整数部分扩展单位
	var cnIntUnits = new Array('', '万', '亿', '兆');
	//对应小数部分单位
	var cnDecUnits = new Array('角', '分', '毫', '厘');
	//整数金额时后面跟的字符
	var cnInteger = '整';
	//整型完以后的单位
	var cnIntLast = '圆';
	//最大处理的数字
	var maxNum = 999999999999999.9999;
	//金额整数部分
	var integerNum;
	//金额小数部分
	var decimalNum;
	//输出的中文金额字符串
	var chineseStr = '';
	//分离金额后用的数组，预定义
	var parts;
	// 传入的参数为空情况
	if(money == '') {
		return '';
	}
	money = parseFloat(money)
	if(money >= maxNum){
		return ''
	}
	// 传入的参数为0情况
	if(money == 0) {
		chineseStr = cnNums[0] + cnIntLast + cnInteger;
		return chineseStr
	}
	// 转为字符串
	money = money.toString();
	// indexOf 检测某字符在字符串中首次出现的位置 返回索引值（从0 开始） -1 代表无
	if(money.indexOf('.') == -1){
		integerNum = money;
		decimalNum = ''
	}else{
		parts = money.split('.');
		integerNum = parts[0];
		decimalNum = parts[1].substr(0,4);
	}
	//转换整数部分
	if(parseInt(integerNum,10) > 0){
		let zeroCount  = 0;
		let IntLen = integerNum.length
		for(let i = 0; i < IntLen; i++){
			let n = integerNum.substr(i,1);
			let p = IntLen - i - 1;
			let q = p / 4;
			let m = p % 4;
			if( n == '0'){
				zeroCount ++ ;
			}else{
				if(zeroCount > 0){
					chineseStr += cnNums[0]
				}
				zeroCount = 0;
				chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
			}
			if(m == 0 && zeroCount < 4){
				chineseStr += cnIntUnits[q];
			}
		}
		// 最后+ 元
		chineseStr += cnIntLast;
	}
	// 转换小数部分
	if(decimalNum != ''){
		let decLen = decimalNum.length;
		for(let i = 0; i <decLen; i++){
			let n = decimalNum.substr(i,1);
			if(n != '0'){
				chineseStr += cnNums[Number(n)] + cnDecUnits[i]
			}
		}
	}
	if(chineseStr == ''){
		chineseStr += cnNums[0] + cnIntLast + cnInteger;
	}else if(decimalNum == ''){
		chineseStr += cnInteger;
	}

	return chineseStr
}

function convertDate(toDate) {//转换带时间分区格式
	var date = new Date(toDate).toJSON();

	var nowDate = new Date(+new Date(date).getTime() + 8 * 3600 * 1000).toISOString().replace(/T/g,' ').replace(/\.[\d]{3}Z/,'');

	return nowDate;
}
function getDiffDay(date1, date2) {//计算两天相差几天
	// 计算两个日期之间的差值
	let totalDays,diffDate;
	let myDate_1 = Date.parse(date1);
	let myDate_2 = Date.parse(date2);
	// 将两个日期都转换为毫秒格式，然后做差
	diffDate = myDate_2 - myDate_1; // 取相差毫秒数的绝对值

	totalDays = Math.floor(diffDate / (1000 * 3600 * 24)); // 向下取整

	return totalDays;    // 相差的天数
}

// 使用

/**
 * 判断是否图片
 * @param ext
 * @returns {boolean}
 */
function isAssetTypeAnImage(name) {
    var i = name.lastIndexOf(".");
    if(i > -1){
        var ext = name.substring(i);
        ext = ext.toLocaleUpperCase();
        return [
            '.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp', '.psd', '.svg', '.tiff'].
        indexOf(ext.toLowerCase()) !== -1;
    }else {
        return false;
    }
}

/**
 * 根据文件名称(包含后缀名)判断是否office文件
 * @param name
 * @returns {boolean}
 */
function isAssetTypeAnOffice(name) {
    var i = name.lastIndexOf(".");
    if(i > -1){
        var ext = name.substring(i);
        ext = ext.toLocaleUpperCase();
        return [
            '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx'].
        indexOf(ext.toLowerCase()) !== -1;
    }else {
        return false;
    }
}

/**
 * 根据文件名称(包含后缀名)判断是否pdf文件
 * @param name
 * @returns {boolean}
 */
function isAssetTypeAnPdf(name) {
    var i = name.lastIndexOf(".");
    if(i > -1){
        var ext = name.substring(i);
        ext = ext.toLocaleUpperCase();
        return ['.pdf'].indexOf(ext.toLowerCase()) !== -1;
    }else {
        return false;
    }
}

/**
 * 预览oa文件
 * @param fid           文件id
 * @param fname         文件名
 */
function previewOAFile(fid,fname) {
    if(isAssetTypeAnOffice(fname)){
        // office文件
        /*var protocol = window.location.protocol;
        let baseUrl = window.location.host;*/
        let origin = window.location.origin;
        let url = origin + "/file/down/" + fid;
        console.log(url);
        url = "https://view.officeapps.live.com/op/view.aspx?src=" + url;
        window.open(url,'_target');
    }else if(isAssetTypeAnPdf(fname)){
        // pdf文件
        /*var protocol = window.location.protocol;
        let baseUrl = window.location.host;
        let url = protocol + baseUrl + "/file/down/" + fid;
        console.log(url);
        url = "http://xudun.chixugroup.com/pdf.html?file=" + url;
        window.open(url,'_target');*/
        window.location.href = "/cloud/preview/pdf?fid=" + fid;
    }else {
        // 其他类型文件,直接下载
        let url = "/file/down/" + fid;
        window.location.href = url;
    }
}
/**
 * 导出文件方法
 * @param url           导出文件的url
 * @param params        传入后台参数
 * @param loadFuc       加载框
 * @param comFuc        ajax执行完成的参数
 * @param sucFuc        请求成功的参数         success最后执行
 * @param errFuc        请求失败的参数
 */
function exportData(url,params,loadFuc,comFuc,sucFuc,errFuc) {
    if(loadFuc != null){
        loadFuc();
    }
    $.ajax({
        type : "POST", //提交方式
        url : url,//路径
        xhrFields: { responseType: "arraybuffer" },
        data: params,
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", "xxx");
        },
        success : function(result,textStatus, request) {
            let responseHeader = decodeURIComponent(escape(request.getResponseHeader("Content-Disposition")));
            let s = responseHeader.split("filename=");
            let filename = s[1];
            const blob = new Blob([result], {type:"application/vnd.ms-excel"});
            if(blob.size < 1) {
                alert('导出失败，导出的内容为空！');
                return
            }
            if(window.navigator.msSaveOrOpenBlob) {
                navigator.msSaveOrOpenBlob(blob, filename)
            } else {
                const aLink = document.createElement('a');
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(blob);
                aLink.download = filename;
                document.body.appendChild(aLink);
                aLink.click();
                document.body.removeChild(aLink);
            }
            if(sucFuc != null){
                sucFuc();
            }
        },
        error:function(){
            if(errFuc != null){
                errFuc();
            }
        },
        complete:function () {
            if(comFuc != null){
                comFuc();
            }
        }
    });
}

function validateMealStandard(e){//金额保留两位小数
	var val = $(e).val();
	var t = val.charAt(0);
	var standard = val.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '');
	if (standard >= 999999999.99){
		if (t == '-')
			$(e).val('-' + 999999999.99);
		else
			$(e).val(999999999.99);
	}else {
		if (t == '-')
			$(e).val('-' + standard);
		else
			$(e).val(standard);
	}
}